import os

from django import http
from django.shortcuts import render

# Create your views here.
# 测试账号：axirmj7487@sandbox.com
from django.views import View

from apps.order.models import OrderInfo

from meiduoproject import settings
from utils.response_code import RETCODE
from utils.views import LoginRequiredJSONMixin
from alipay import AliPay


# 订单支付
class PayUrlView(LoginRequiredJSONMixin,View):
    """订单支付功能"""

    def get(self,request, order_id):

        try:
            order = OrderInfo.objects.get(order_id=order_id,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'],
                                          user=request.user)
        except OrderInfo.DoesNotExist:
            return http.HttpResponseBadRequest('订单信息错误')
        # 1.创建alipay实例

        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()

        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()


        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2", # RSA 或者 RSA2
            debug = settings.DEBUG  # 默认False
        )

        # 2.调用网站支付方法(接口),生成order_string
        # 如果你是 Python 3的用户，使用默认的字符串即可
        subject = "测试订单"

        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id, #订单id
            total_amount=str(order.total_amount),
            subject=subject,
            return_url=settings.ALIPAY_RETURN_URL, #回调

        )
        # 3.拼接支付的url
        pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
        # 4.返回这个url
        return http.JsonResponse({'code':RETCODE.OK,'alipay_url':pay_url})

# 保存订单  订单显示
class PaymentStatusView(View):
    """保存订单支付结果"""

    def get(self, request):
        data = request.GET.dict()

        signature = data.pop("sign")

        # verification
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()

        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.DEBUG  # 默认False
        )
        # 2.根据验证方法判断是否真的成功
        success = alipay.verify(data, signature)
        # 成功则保存
        if success:
            # 订单号
            out_trade_no = data.get('out_trade_no')
            # 读取支付宝流水号
            trade_no = data.get('trade_no')
            # 保存Payment模型类数据
            from apps.payment.models import Payment
            Payment.objects.create(
                order_id=out_trade_no,
                trade_id=trade_no,
            )
            # 修改订单状态为待评价
            OrderInfo.objects.filter(order_id=out_trade_no).update(status=OrderInfo.ORDER_STATUS_ENUM["UNSEND"])

        return render(request,'pay_success.html',context={'trade_id':trade_no})

